use regex::Regex;

pub fn transform_ten(num_str: &str, from_base: u32) -> u32 {
    //将from_base进制的num_str转换为十进制
    let mut num = 0;
    let mut base = 1;
    for c in num_str.chars().rev() {
        let digit = c.to_digit(10).unwrap();
        num += digit * base;
        base *= from_base;
    }
    num
}

pub fn convert_base(num_str: &str, to_base: u32) -> String {
    //进制转换，a进制转换为to_base进制,num_str形式为num(a）
    let re = Regex::new(r"(\d+)\((\d+)\)").unwrap();
    let cap = re.captures(num_str).unwrap();
    let num = cap.get(1).unwrap().as_str();
    let from_base = cap.get(2).unwrap().as_str().parse::<u32>().unwrap();
    let num = transform_ten(num, from_base);
    let mut num = num;
    let mut res = String::new();
    while num > 0 {
        let digit = num % to_base;
        //进制转换，大于9的数字转换为字母
        if digit > 9 {
            res.push((digit - 10 + 'a' as u32) as u8 as char);
        } else {
            res.push_str(&digit.to_string());
        }
        num /= to_base;
    }
    res.chars().rev().collect()
}
